<?php

// +----------------------------------------------------------------------
// | ThinkAdmin
// +----------------------------------------------------------------------
// | 版权所有 2014~2020 广州楚才信息科技有限公司 [ http://www.cuci.cc ]
// +----------------------------------------------------------------------
// | 官方网站: https://thinkadmin.top
// +----------------------------------------------------------------------
// | 开源协议 ( https://mit-license.org )
// +----------------------------------------------------------------------
// | gitee 代码仓库：https://gitee.com/zoujingli/ThinkAdmin
// | github 代码仓库：https://github.com/zoujingli/ThinkAdmin
// +----------------------------------------------------------------------

namespace app\group\command;

use think\admin\Command;
use think\console\Input;
use think\console\Output;

/**
 * 订单处理指令
 * Class Fans
 * @package app\group\command
 */
class Order extends Command
{
    /**
     * 需要处理的模块
     * @var array
     */
    protected $module = ['collect'];

    /**
     * 配置指令
     */
    protected function configure()
    {
        $this->setName('xadmin:orderall')->setDescription('synchronize Update Order Date');
    }

    /**
     * 执行指令
     * @param Input $input
     * @param Output $output
     * @throws \think\admin\Exception
     */
    protected function execute(Input $input, Output $output)
    {
        $message = '';
        foreach ($this->module as $m) {
            if (method_exists($this, $method = "_{$m}")) {
                $message .= $this->$method();
            }
        }
        $this->setQueueSuccess($message);
    }

    /**
     * 判断拼团列表
     * @param int $success
     * @param int $error
     * @return string
     */
    protected function _group($success = 0, $error = 0)
    {
        $this->output->comment('--> Start to synchronize Update Group Date');
        $now_time = date('Y-m-d H:i:s');
        $Model = $this->app->db;
        $group_list = [];
        try {
            $group_list = $Model->name('pt_group_times')
                ->field('b.id,b.limit_num')
                ->alias('a')
                ->join('pt_group_act b', 'b.times_id = a.id')
                ->where([['a.is_forbid', '=', 0], ['b.group_status', '=', 1],
                    ['b.is_forbid', '=', 0], ['a.act_end_time', '<=', $now_time]])
                ->select()->all();
        } catch (\Exception $e) {
            $this->output->comment('--> group_list:' . $e->getMessage());
        }
        foreach ($group_list as $info) {
            $Model->startTrans();
            try {
                $group_status = 3;
                $group_field_time = 'group_error_time';
                $buy_num = $Model->name('pt_son_order')->where([
                    'group_id' => $info['id'],
                    'order_status' => 1,
                ])->sum('num');
                if ($buy_num >= $info['limit_num']) {
                    $bool = $Model->name('pt_son_order')->where([
                        'group_id' => $info['id'],
                        'order_status' => 1,
                    ])->save(['order_status' => 2]);
                    if (!$bool) throw new \Exception('更新订单失败');
                    $group_status = 2;
                    $group_field_time = 'group_succ_time';
                    $success++;
                }
                $bool = $Model->name('pt_group_act')->where([
                    'id' => $info['id'],
                    'group_status' => 1,
                ])->save(['group_status' => $group_status, $group_field_time => $now_time]);
                if (!$bool) throw new \Exception('更新拼团状态失败');
                if ($group_status == 3) $error++;
                $Model->commit();
            } catch (\Exception $e) {
                $error++;
                $Model->rollback();
                $this->output->comment("--> group_id:{$info['id']}" . $e->getMessage());
            }
        }
        $this->output->comment('--> End to synchronize Update Group Date');
        return "拼团成功 {$success} 拼团失败 {$error}";
    }

    /**
     * 自动收货
     * @param int $success
     * @param int $error
     * @return string
     */
    public function _collect($success = 0, $error = 0)
    {
        $this->output->comment('--> Start to synchronize Update Collect Date');
        $now_time = date('Y-m-d H:i:s');
        $Model = $this->app->db;
        $collect_list = [];
        try {
            $collect_list = $Model->name('pt_order_addr')
                ->field('a.id,a.son_id')->alias('a')
                ->join('pt_son_order b', 'a.top_id = b.top_id')
                ->whereNotNull('a.send_time')
                ->whereNotNull('a.receive_time_end')
                ->whereNull('a.receive_time')
                ->where([['b.order_status', '=', 3], ['a.receive_time_end', '<=', $now_time]])
                ->select()->all();
        } catch (\Exception $e) {
            $this->output->comment('--> collect_list:' . $e->getMessage());
        }
        foreach ($collect_list as $item) {
            try {
                $Model->startTrans();
                $bool = $Model->name('pt_order_addr')
                    ->where(['id' => $item])
                    ->whereNotNull('send_time')
                    ->whereNotNull('receive_time_end')
                    ->whereNull('receive_time')
                    ->save(['receive_time' => $now_time]);
                if (!$bool) throw new \Exception('更新发货状态失败');
                $bool = $Model->name('pt_son_order')->where([
                    'son_id' => $item['son_id'],
                    'order_status' => 3,
                ])->save(['order_status' => 4]);
                if (!$bool) throw new \Exception('更新订单失败');
                $Model->commit();
            } catch (\Exception $e) {
                $error++;
                $Model->rollback();
                $this->output->comment("--> id:{$item['id']}" . $e->getMessage());
            }
            $success++;
        }
        $this->output->comment('--> End to synchronize Update Collect Date');
        return "自动收货成功 {$success} 失败 {$error}";
    }
}